import { defineStore } from "pinia";

export const useAddressStore = defineStore("address", {
  state: () => ({
    // 当前选中的地址
    selectedAddress: JSON.parse(localStorage.getItem('selectedAddress')) || null,
    // 所有地址列表
    addresses: JSON.parse(localStorage.getItem('addressList')) || []
  }),

  actions: {
    /**
     * 设置选中的地址
     * @param {Object} address - 地址对象
     */
    setSelectedAddress(address) {
      this.selectedAddress = { ...address };
      localStorage.setItem('selectedAddress', JSON.stringify(address));
    },

    /**
     * 保存地址（新增或编辑）
     * @param {Object} address - 地址对象
     * @returns {string} 返回地址ID
     */
    saveAddress(address) {
      const isEdit = !!address.id;
      
      // 新增地址时生成ID
      if (!isEdit) {
        address.id = Date.now().toString();
      }
      
      // 更新地址列表
      const index = this.addresses.findIndex(a => a.id === address.id);
      if (index !== -1) {
        this.addresses.splice(index, 1, address);
      } else {
        this.addresses.push(address);
      }
      
      // 处理默认地址逻辑
      if (address.isDefault) {
        this.setAsDefault(address.id);
      } else if (this.addresses.length === 1) {
        // 如果是唯一地址，自动设为默认
        address.isDefault = true;
        this.addresses[0].isDefault = true;
      }

      this.saveAddressData();
      
      // 更新当前选中地址
      if (this.selectedAddress?.id === address.id) {
        this.setSelectedAddress(address);
      }
      
      return address.id;
    },

    /**
     * 删除地址
     * @param {string} id - 地址ID
     */
    deleteAddress(id) {
      // 从地址列表删除
      this.addresses = this.addresses.filter(a => a.id !== id);
      
      // 处理被删除的是当前选中地址的情况
      if (this.selectedAddress?.id === id) {
        this.selectedAddress = null;
        localStorage.removeItem('selectedAddress');
      }
      
      // 如果删除的是默认地址，设置第一个地址为默认
      const hasDefault = this.addresses.some(a => a.isDefault);
      if (!hasDefault && this.addresses.length > 0) {
        this.addresses[0].isDefault = true;
        if (!this.selectedAddress) {
          this.setSelectedAddress(this.addresses[0]);
        }
      }
      
      this.saveAddressData();
    },

    /**
     * 设为默认地址
     * @param {string} id - 地址ID
     */
    setAsDefault(id) {
      this.addresses = this.addresses.map(a => ({
        ...a,
        isDefault: a.id === id
      }));
      
      const defaultAddr = this.addresses.find(a => a.id === id);
      if (defaultAddr) {
        this.setSelectedAddress(defaultAddr);
      }
      
      this.saveAddressData();
    },

    /**
     * 保存地址数据到本地存储
     */
    saveAddressData() {
      localStorage.setItem('addressList', JSON.stringify(this.addresses));
    },

    /**
     * 从本地存储初始化数据
     */
    initializeFromLocalStorage() {
      this.selectedAddress = JSON.parse(localStorage.getItem('selectedAddress')) || null;
      this.addresses = JSON.parse(localStorage.getItem('addressList')) || [];
    }
  },

  getters: {
    /**
     * 获取默认地址
     * @returns {Object|null} 默认地址对象
     */
    defaultAddress: (state) => 
      state.addresses.find(address => address.isDefault) || null,

    /**
     * 获取排序后的地址列表（默认地址在前）
     * @returns {Array} 排序后的地址数组
     */
    sortedAddresses: (state) =>
      [...state.addresses].sort((a, b) => 
        (b.isDefault ? 1 : 0) - (a.isDefault ? 1 : 0)),

    /**
     * 拼接完整地址字符串
     * @param {Object} address - 地址对象
     * @returns {string} 完整地址字符串
     */
    fullAddress: (state) => (address) => {
      if (!address) return '';
      return `${address.province}${address.city}${address.county}${address.addressDetail}`;
    },

    /**
     * 根据ID获取地址
     * @param {string} id - 地址ID
     * @returns {Object|undefined} 地址对象
     */
    getAddressById: (state) => (id) => {
      return state.addresses.find(address => address.id === id);
    }
  },

  // Pinia持久化配置
  persist: {
    enabled: true,
    strategies: [
      {
        key: "address",
        storage: localStorage,
        paths: ['addresses', 'selectedAddress']
      }
    ]
  }
});